package com.wl.dzt.ide.service;

import com.wl.dzt.sys.core.dao.mate.DataMateBase;
import com.wl.dzt.sys.core.dao.mate.DataMateTable;
import com.wl.dzt.sys.core.dao.tree.TreeBuilder;
import com.wl.dzt.sys.core.dao.tree.TreeSetting;
import com.wl.dzt.sys.fmk.Fmkr;
import com.wl.dzt.sys.util.SystemUtil;
import com.wl.dzt.sys.util.clazz.ClassUtil;
import com.wl.dzt.sys.util.json.Json;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 脚本生成
 */
@Service
public class ScriptGenderService {

    /**
     * <b>查询所有的实体</b>
     * <p>
     * 查询所有的实体
     * </p>
     *
     * @return
     */
    public List<Map<String, Object>> entityList() {
        List<DataMateTable> list = new ArrayList<>();
        DataMateBase.getAllTales().forEach((clazz, entity) -> list.add(entity));
        return TreeBuilder.cascadeTree(list, TreeSetting.createByExp("entityClass,entityClass,*"));
    }

    /**
     * <b>根据模板类型生模板</b>
     * <p>
     * 根据模板类型生模板
     * </p>
     *
     * @param modelType
     * @param clazz
     */
    public void createScript(String modelType, String clazz) {
        Map<String, Object> data = new HashMap<>();
        Class<?> entityClass = ClassUtil.createClass(clazz);
        DataMateTable dataMateTable = DataMateBase.getTable(entityClass);
        List<Map<String, String>> cols = new ArrayList<>();
        dataMateTable.getColumns().forEach((key, col) -> {
            if (!"id".equals(col.getFieldName())) {
                Map<String, String> row = new HashMap<>();
                row.put("name", col.getFieldName());
                cols.add(row);
            }
        });
        String name = entityClass.getSimpleName();
        data.put("clazz", name);
        data.put("main", name + "_main");
        data.put("form", name + "_form");
        data.put("cols", Json.parse(cols));
        //默认寻找template目录
        Fmkr.builder(modelType, data, String.format("%s/%s.js", SystemUtil.getDasktopPath(), name));
    }
}
